package http

import (
	"log"
	"net/http"
	"time"
)

type Job interface {
	Log(...interface{})
	Suspend() error
	Resume() error
	Run() error
}

type PollerJob struct {
	suspend      chan bool
	resume       chan bool
	resuourceUrl string
	inMemLog     string
}

func NewPollerJob(resourceUrl string) PollerJob {
	return PollerJob{
		resourceUrl: resourceUrl,
		suspend:     make(chan bool),
		resume:      make(chan bool),
	}
}

func (p PollerJob) Log(args ...interface{}) {
	log.Println(args...)
}

func (p PollerJob) Suspend() error {
	p.suspend <- true
	return nil
}

func (p PollerJob) PollServer() error {
	resp, err := http.Get(p.resuourceUrl)
	if err != nil {
		return err
	}

	p.Log(p.resuourceUrl, "--", resp.Status)

	return nil
}

func (p PollerJob) Run() error {
	for {
		select {
		case <-p.suspend:
			<-p.resume
		default:
			if err := p.PollServer(); err != nil {
				p.Log("Error trying to get resource:", err)
			}
			tiem.Sleep(1 * time.Second)
		}
	}
}
